<script setup>
import {message} from 'ant-design-vue';
import {ref} from 'vue';
import {noticeAdd, noticeUpdate, noticeOne} from '@/api/noticeApi.js';
import * as commonDict from '@/utils/commonDict.js'


const open = ref(false);
const formRef = ref(null);
const emits = defineEmits(['saveSuccessful'])
import {loading} from '@/utils/loadingUtils.js';
import dayjs from 'dayjs';
import Base64FilesUpload from '@/components/Base64FilesUpload.vue';

const form = ref({
  title: '',
  content: '',
  files:[],
  publishDate: undefined,
  status: undefined,
  createTime: '',
})

const onOpen = (id) => {
  if (id) {
    handleUpdate(id)
  }
  open.value = true
}

const handleUpdate = (id) => {
  noticeOne(id).then(res => {
    form.value = res
    form.value.publishDate = dayjs(form.value.publishDate,'YYYY-MM-DD')

    onOpen()
  })
}
const onClose = () => {
  open.value = false
  resetForm()
}


const resetForm = () => {
  formRef.value.resetFields();
  form.value.id = ''
};


const submit = () => {
  formRef.value.validate().then(async () => {
    if (form.value.id) {
      await noticeUpdate(form.value)
    } else {
      await noticeAdd(form.value)
    }
    message.success(form.value.id ? '更新成功' : '保存成功')
    emits('saveSuccessful')
    onClose()
  })
}

defineExpose({
  onOpen
})
</script>

<template>

  <a-modal @ok="submit" v-model:open="open" width="700px" @cancel="onClose" @close="onClose">
    <a-form :model="form" ref="formRef" layout="vertical">
      <a-form-item
          label="标题"
          name="title"
          :rules="[{ required: true, message: '请输入标题' }]"
      >
        <a-input
            placeholder="请输入标题"
            v-model:value="form.title"></a-input>
      </a-form-item>
      <a-form-item
          label="请上传封面"
          name="files"
          :rules="[{ required: true, message: '请上传封面' }]"
      >
        <base64-files-upload :limit="1" v-model="form.files"></base64-files-upload>
      </a-form-item>
      <a-form-item
          label="内容"
          name="content"
          :rules="[{ required: true, message: '请输入内容' }]"
      >
        <a-input
            placeholder="请输入内容"
            v-model:value="form.content"></a-input>
      </a-form-item>
      <a-form-item
          label="发布日期"
          name="publishDate"
          value-format="YYYY-MM-DD"
          :rules="[{ required: true, message: '请输入发布日期' }]"
      >
        <a-date-picker v-model:value="form.publishDate">
        </a-date-picker>
      </a-form-item>
      <a-form-item
          label="状态"
          name="status"
          :rules="[{ required: true, message: '请输入状态' }]"
      >
        <a-select
            placeholder="请输入状态"
            :options="Object.keys(commonDict.pubStatus).map(x => ({label:commonDict.pubStatus[x] ,value:x}))"
            v-model:value="form.status">
        </a-select>
      </a-form-item>

    </a-form>
  </a-modal>

</template>

<style scoped>

</style>
